using System;
using System.Diagnostics;

namespace LightPersist.Metainfo
{
	public class TypeResolver
	{
		private Type _typeClr;

		protected internal void TypeClrInvalidate()
		{
			_typeClr = null;
		}

		protected internal bool TryResolveType()
		{
#if DEBUG
			Debug.Assert(_typeClr == null);
#endif
			try
			{
				LightProfiling.Lap("Resolving type " + TypeName);
				_typeClr = Type.GetType(TypeName);
				LightProfiling.Lap("Resolving type done");
			}
			catch (Exception ex)
			{
				Trace.WriteLine("Type Not Found: " + TypeName + Environment.NewLine + ex.Message, "ERROR");
			}
			return _typeClr != null;
		}

		/// <summary>
		/// This field speedup loading by avoid type resolving
		/// </summary>
		[CodeInitializer("typeof({0})", "TypeNameFull")]
		public Type TypeClrPersist
		{
			get { return _typeClr; }
			set { _typeClr = value; }
		}

		protected internal Type TypeClr
		{
			get
			{
				if (_typeClr == null)
				{
					if (!TryResolveType())
					{
						throw new ApplicationException("Unknown type: " + TypeName);
					}
				}
				return _typeClr;
			}
		}

		protected internal string TypeName { get; set; }

		public string TypeNameFull
		{
			get
			{
				return DomainMetainfo.GetFullNameFromAqn(TypeName);
			}
		}
	}
}